package com.example.netty.handler;

import com.example.netty.common.Message;
import com.example.netty.service.GameService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zclever <304078606@qq.com>
 * @date 2021-03-02
 */
@Component
@ChannelHandler.Sharable
public class CommonHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger logger = LoggerFactory.getLogger(CommonHandler.class);

    @Autowired
    GameService gameService;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("用户{}连接", ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("用户{}断开", ctx.channel().remoteAddress());

        //用户掉线,删除用户和匹配队列
        Message res = gameService.outGame(ctx.channel());
        ctx.channel().writeAndFlush(res.toMsg());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        logger.info("用户发送消息:{}", msg.text());

        msg.retain();
        ctx.fireChannelRead(msg);

    }
}